package com.seisys.controller.system.login;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.seisys.common.annotation.Anoymous;
import com.seisys.controller.base.BaseController;
import com.seisys.dao.JedisClient;
import com.seisys.dto.CheckAuthRequest;
import com.seisys.dto.CheckAuthResponse;
import com.seisys.entity.system.Menu;
import com.seisys.entity.system.Role;
import com.seisys.entity.system.User;
import com.seisys.service.system.macaddr.MacAddrService;
import com.seisys.service.system.menu.MenuService;
import com.seisys.service.system.role.RoleService;
import com.seisys.service.system.user.UserService;
import com.seisys.util.AppUtil;
import com.seisys.util.Const;
import com.seisys.util.CookieUtil;
import com.seisys.util.DateUtil;
import com.seisys.util.JwtTokenUtils;
import com.seisys.util.PageData;
import com.seisys.util.RightsHelper;
import com.seisys.util.Tools;

import io.jsonwebtoken.Claims;

/*
 * 总入口
 */
@Controller
public class LoginController extends BaseController {

	@Resource(name = "userService")
	private UserService userService;
	@Resource(name = "menuService")
	private MenuService menuService;
	@Resource(name = "roleService")
	private RoleService roleService;
	@Resource(name = "macAddrService")
	private MacAddrService macAddrService;

	private final String ACCESS_TOKEN = "access_token";

	/**
	 * 获取登录用户的IP
	 * 
	 * @throws Exception
	 */
	public void getRemortIP(String USERNAME) throws Exception {
		PageData pd = new PageData();
		HttpServletRequest request = this.getRequest();
		String ip = "";
		if (request.getHeader("x-forwarded-for") == null) {
			ip = request.getRemoteAddr();
		} else {
			ip = request.getHeader("x-forwarded-for");
		}
		pd.put("USERNAME", USERNAME);
		pd.put("IP", ip);
		userService.saveIP(pd);
	}

	/**
	 * 访问登录页
	 * 
	 * @return
	 */
	@Anoymous
	@RequestMapping(value = "/login_toLogin")
	public ModelAndView toLogin() throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); // 读取系统名称
		mv.setViewName("system/admin/login");
		mv.addObject("pd", pd);
		return mv;
	}

	/**
	 * 验证token是否有效
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/validToken", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object validToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String token = CookieUtil.getCookieValue(request, ACCESS_TOKEN);
		boolean isAjax = CookieUtil.isAjax(request);
		if (StringUtils.isEmpty(token)) {
			if (isAjax) {
				map.put("code", "-1");
				map.put("msg", "error");
			}
			// 返回登录页面
		}
		CheckAuthRequest checkAuthRequest = new CheckAuthRequest();
		checkAuthRequest.setToken(token);
		CheckAuthResponse checkAuthResponse = userService.validToken(checkAuthRequest);
		if ("00000".equals(checkAuthResponse.getCode())) {

		}
		if (isAjax) {
			map.put("uid", checkAuthResponse.getUid());
			map.put("code", checkAuthResponse.getCode());
			map.put("msg", checkAuthResponse.getMsg());
			map.put("token", token);
		}
		return map;
	}

	/**
	 * 请求登录，验证用户
	 */
	@Anoymous
	@RequestMapping(value = "/login_login", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object login(HttpServletResponse response) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String errInfo = "";
		String KEYDATA[] = pd.getString("KEYDATA").replaceAll("en1010001100fx", "").replaceAll("EN011110010fx", "")
				.split(",fx,");
		//
		// shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		String sessionCode = (String) session.getAttribute(Const.SESSION_SECURITY_CODE); // 获取session中的验证码

		String code = KEYDATA[2];
		if (null == code || "".equals(code)) {
			errInfo = "nullcode"; // 验证码为空
		} else {
			String USERNAME = KEYDATA[0];
			String PASSWORD = KEYDATA[1];
			pd.put("USERNAME", USERNAME);
			if (Tools.notEmpty(sessionCode) && sessionCode.equalsIgnoreCase(code)) {
				String passwd = new SimpleHash("SHA-1", USERNAME, PASSWORD).toString(); // 密码加密
				pd.put("PASSWORD", passwd);
				pd = userService.getUserByNameAndPwd(pd);// --生成token方法
				if (pd != null) {
					pd.put("LAST_LOGIN", DateUtil.getTime().toString());
					userService.updateLastLogin(pd);
					User user = new User();
					user.setUSER_ID(pd.getString("USER_ID"));
					user.setUSERNAME(pd.getString("USERNAME"));
//					user.setPASSWORD(pd.getString("PASSWORD"));
					user.setPASSWORD("passwd");
					user.setNAME(pd.getString("NAME"));
					user.setRIGHTS(pd.getString("RIGHTS"));
					user.setROLE_ID(pd.getString("ROLE_ID"));
					user.setLAST_LOGIN(pd.getString("LAST_LOGIN"));
					user.setIP(pd.getString("IP"));
					user.setSTATUS(pd.getString("STATUS"));
					session.setAttribute(pd.get("token"), user);
					session.setAttribute(Const.SESSION_USER, user);
					session.removeAttribute(Const.SESSION_SECURITY_CODE);
					user = userService.getUserRoleById(user.getUSER_ID());
					session.setAttribute(Const.SESSION_USERROL, user);
					response.addHeader("Access-Control-Allow-Credentials", "true");// 跨域发送
					response.addHeader("Set-Cookie", "access_token=" + pd.getString("token") + ";Path=/;HttpOnly"+"Domain=127.0.0.1;");

					// shiro加入身份验证
					Subject subject = SecurityUtils.getSubject();
					UsernamePasswordToken token = new UsernamePasswordToken(USERNAME, user.getPASSWORD());// passwd
					try {
						subject.login(token);
					} catch (AuthenticationException e) {
						errInfo = "身份验证失败！";
					}
					map.put("USER_ID", user.getUSER_ID());
					map.put("USERNAME", user.getUSERNAME());

					map.put("code", pd.getString("code"));
					map.put("msg", pd.getString("msg"));
					map.put("token", pd.getString("token"));
				} else {
					errInfo = "usererror"; // 用户名或密码有误
				}
			} else {
				errInfo = "codeerror"; // 验证码输入有误
			}
			if (Tools.isEmpty(errInfo)) {
				errInfo = "success"; // 验证成功
			}
		}

		map.put("result", errInfo);
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 访问平台系统选择页
	 */
	@RequestMapping(value = "main/navigation")
	public ModelAndView login_navigation() {
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {

			// shiro管理的session
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();

			User user = (User) session.getAttribute(Const.SESSION_USER);
			if (user != null) {

				User userr = (User) session.getAttribute(Const.SESSION_USERROL);
				if (null == userr) {
					user = userService.getUserAndRoleById(user.getUSER_ID());
					session.setAttribute(Const.SESSION_USERROL, user);
				} else {
					user = userr;
				}
				// 取得上下文中的role
				Role role = user.getRole();
				// 更新上下文种的role
				Role role1 = updateRoleRights(role);
				user.setRole(role1);
				String roleRights = role1 != null ? role1.getRIGHTS() : "";
				// 避免每次拦截用户操作时查询数据库，以下将用户所属角色权限、用户权限限都存入session
				session.setAttribute(Const.SESSION_ROLE_RIGHTS, roleRights); // 将角色权限存入session
				session.setAttribute(Const.SESSION_USERNAME, user.getUSERNAME()); // 放入用户名

				List<Menu> allmenuList = new ArrayList<Menu>();

				if (null == session.getAttribute(Const.SESSION_allmenuList)) {
					allmenuList = menuService.listAllMenu();
					if (Tools.notEmpty(roleRights)) {
						for (Menu menu : allmenuList) {
							menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMENU_ID()));
							if (menu.isHasMenu()) {
								List<Menu> subMenuList = menu.getSubMenu();
								for (Menu sub : subMenuList) {
									sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMENU_ID()));
									if (sub.isHasMenu()) {
										List<Menu> triMenuList = sub.getSubMenu();
										for (Menu triMenu : triMenuList) {
											triMenu.setHasMenu(
													RightsHelper.testRights(roleRights, triMenu.getMENU_ID()));
										}
									}
								}
							}
						}
					}
					session.setAttribute(Const.SESSION_allmenuList, allmenuList); // 菜单权限放入session中
				} else {
					// allmenuList = (List<Menu>) session
					// .getAttribute(Const.SESSION_allmenuList);
					allmenuList = menuService.listAllMenu();
					if (Tools.notEmpty(roleRights)) {
						for (Menu menu : allmenuList) {
							menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMENU_ID()));
							if (menu.isHasMenu()) {
								List<Menu> subMenuList = menu.getSubMenu();
								for (Menu sub : subMenuList) {
									sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMENU_ID()));
									if (sub.isHasMenu()) {
										List<Menu> triMenuList = sub.getSubMenu();
										for (Menu triMenu : triMenuList) {
											triMenu.setHasMenu(
													RightsHelper.testRights(roleRights, triMenu.getMENU_ID()));
										}
									}
								}
							}
						}
					}
					session.setAttribute(Const.SESSION_allmenuList, allmenuList); // 菜单权限放入session中
				}

				// 切换菜单=====
				List<Menu> menuList = new ArrayList<Menu>();
				menuList = allmenuList;
				// 切换菜单=====

				if (null == session.getAttribute(Const.SESSION_QX)) {
					session.setAttribute(Const.SESSION_QX, this.getUQX(session)); // 按钮权限放到session中
				}

				// FusionCharts 报表
				// String strXML = "<graph caption='前12个月订单销量柱状图' xAxisName='月份'
				// yAxisName='值' "
				// + "decimalPrecision='0' formatNumberScale='0'><set
				// name='2013-05' value='4' "
				// + "color='AFD8F8'/><set name='2013-04' value='0'
				// color='AFD8F8'/><set name='2013-03' "
				// + "value='0' color='AFD8F8'/><set name='2013-02' value='0'
				// color='AFD8F8'/>"
				// + "<set name='2013-01' value='0' color='AFD8F8'/><set
				// name='2012-01' value='0' "
				// + "color='AFD8F8'/><set name='2012-11' value='0'
				// color='AFD8F8'/><set name='2012-10' "
				// + "value='0' color='AFD8F8'/><set name='2012-09' value='0'
				// color='AFD8F8'/>"
				// + "<set name='2012-08' value='0' color='AFD8F8'/><set
				// name='2012-07' value='0'"
				// + " color='AFD8F8'/><set name='2012-06' value='0'
				// color='AFD8F8'/></graph>";
				// mv.addObject("strXML", strXML);
				// FusionCharts 报表

				mv.setViewName("system/admin/navigation");
				mv.addObject("user", user);
				mv.addObject("menuList", menuList);
			} else {
				mv.setViewName("system/admin/login");// session失效后跳转登录页面
				// mv.setViewName("redirect:"+Tools.readTxtFile(Const.SYSLOGIN));
			}

		} catch (Exception e) {
			mv.setViewName("system/admin/login");
			// mv.setViewName("redirect:"+Tools.readTxtFile(Const.SYSLOGIN));
			logger.error(e.getMessage(), e);
		}
		pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); // 读取系统名称
		mv.addObject("pd", pd);
		return mv;
	}

	/**
	 * 访问新平台系统选择页
	 */
	@RequestMapping(value = "main/navigation_new")
	public ModelAndView login_navigation_new() {
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {

			// shiro管理的session
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();

			User user = (User) session.getAttribute(Const.SESSION_USER);
			if (user != null) {

				User userr = (User) session.getAttribute(Const.SESSION_USERROL);
				if (null == userr) {
					user = userService.getUserRoleById(user.getUSER_ID());
					session.setAttribute(Const.SESSION_USERROL, user);
				} else {
					user = userr;
				}
				// 取得上下文中的role
				Role role = user.getRole();
				// 更新上下文种的role
				Role role1 = updateRoleRights(role);
				user.setRole(role1);
				String roleRights = role1 != null ? role1.getRIGHTS() : "";
				// 避免每次拦截用户操作时查询数据库，以下将用户所属角色权限、用户权限限都存入session
				session.setAttribute(Const.SESSION_ROLE_RIGHTS, roleRights); // 将角色权限存入session
				session.setAttribute(Const.SESSION_USERNAME, user.getUSERNAME()); // 放入用户名

				List<Menu> allmenuList = new ArrayList<Menu>();

				if (null == session.getAttribute(Const.SESSION_allmenuList)) {
					allmenuList = menuService.listAllMenu();
					if (Tools.notEmpty(roleRights)) {
						for (Menu menu : allmenuList) {
							menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMENU_ID()));
							if (menu.isHasMenu()) {
								List<Menu> subMenuList = menu.getSubMenu();
								for (Menu sub : subMenuList) {
									sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMENU_ID()));
									if (sub.isHasMenu()) {
										List<Menu> triMenuList = sub.getSubMenu();
										for (Menu triMenu : triMenuList) {
											triMenu.setHasMenu(
													RightsHelper.testRights(roleRights, triMenu.getMENU_ID()));
										}
									}
								}
							}
						}
					}
					session.setAttribute(Const.SESSION_allmenuList, allmenuList); // 菜单权限放入session中
				} else {
					// allmenuList = (List<Menu>) session
					// .getAttribute(Const.SESSION_allmenuList);
					allmenuList = menuService.listAllMenu();
					if (Tools.notEmpty(roleRights)) {
						for (Menu menu : allmenuList) {
							menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMENU_ID()));
							if (menu.isHasMenu()) {
								List<Menu> subMenuList = menu.getSubMenu();
								for (Menu sub : subMenuList) {
									sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMENU_ID()));
									if (sub.isHasMenu()) {
										List<Menu> triMenuList = sub.getSubMenu();
										for (Menu triMenu : triMenuList) {
											triMenu.setHasMenu(
													RightsHelper.testRights(roleRights, triMenu.getMENU_ID()));
										}
									}
								}
							}
						}
					}
					session.setAttribute(Const.SESSION_allmenuList, allmenuList); // 菜单权限放入session中
				}

				// 切换菜单=====
				List<Menu> menuList = new ArrayList<Menu>();
				menuList = allmenuList;
				// 切换菜单=====

				if (null == session.getAttribute(Const.SESSION_QX)) {
					session.setAttribute(Const.SESSION_QX, this.getUQX(session)); // 按钮权限放到session中
				}

				// FusionCharts 报表
				// String strXML = "<graph caption='前12个月订单销量柱状图' xAxisName='月份'
				// yAxisName='值' "
				// + "decimalPrecision='0' formatNumberScale='0'><set
				// name='2013-05' value='4' "
				// + "color='AFD8F8'/><set name='2013-04' value='0'
				// color='AFD8F8'/><set name='2013-03' "
				// + "value='0' color='AFD8F8'/><set name='2013-02' value='0'
				// color='AFD8F8'/>"
				// + "<set name='2013-01' value='0' color='AFD8F8'/><set
				// name='2012-01' value='0' "
				// + "color='AFD8F8'/><set name='2012-11' value='0'
				// color='AFD8F8'/><set name='2012-10' "
				// + "value='0' color='AFD8F8'/><set name='2012-09' value='0'
				// color='AFD8F8'/>"
				// + "<set name='2012-08' value='0' color='AFD8F8'/><set
				// name='2012-07' value='0'"
				// + " color='AFD8F8'/><set name='2012-06' value='0'
				// color='AFD8F8'/></graph>";
				// mv.addObject("strXML", strXML);
				// FusionCharts 报表

				mv.setViewName("system/admin/navigation_new");
				mv.addObject("user", user);
				mv.addObject("menuList", menuList);
			} else {
				mv.setViewName("system/admin/login");// session失效后跳转登录页面
				// mv.setViewName("redirect:"+Tools.readTxtFile(Const.SYSLOGIN));
			}

		} catch (Exception e) {
			mv.setViewName("system/admin/login");
			// mv.setViewName("redirect:"+Tools.readTxtFile(Const.SYSLOGIN));
			logger.error(e.getMessage(), e);
		}
		pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); // 读取系统名称
		mv.addObject("pd", pd);
		return mv;
	}

	/**
	 * 访问系统首页
	 */
	/*
	 * @SuppressWarnings("unchecked")
	 * 
	 * @RequestMapping(value = "/main/{changeMenu}") public ModelAndView
	 * login_index(@PathVariable("changeMenu") String changeMenu) { ModelAndView mv
	 * = this.getModelAndView(); PageData pd = new PageData(); pd =
	 * this.getPageData(); try {
	 * 
	 * // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session
	 * session = currentUser.getSession(); User user = (User)
	 * session.getAttribute(Const.SESSION_USER); if (user != null) {
	 * 
	 * User userr = (User) session.getAttribute(Const.SESSION_USERROL); if (null ==
	 * userr) { user = userService.getUserAndRoleById(user.getUSER_ID());
	 * session.setAttribute(Const.SESSION_USERROL, user); } else { user = userr; }
	 * // //取得上下文中的role // Role role = user.getRole(); // //更新上下文种的role // Role
	 * role1 = updateRoleRights(role); // user.setRole(role1); // String roleRights
	 * = role1 != null ? role1.getRIGHTS() : ""; // //
	 * 避免每次拦截用户操作时查询数据库，以下将用户所属角色权限、用户权限限都存入session //
	 * session.setAttribute(Const.SESSION_ROLE_RIGHTS, roleRights); // //
	 * 将角色权限存入session // session.setAttribute(Const.SESSION_USERNAME, //
	 * user.getUSERNAME()); // 放入用户名 // // List<Menu> allmenuList = new
	 * ArrayList<Menu>(); // // if (null ==
	 * session.getAttribute(Const.SESSION_allmenuList)) // { // allmenuList =
	 * menuService.listAllMenu(); // if (Tools.notEmpty(roleRights)) { // for (Menu
	 * menu : allmenuList) { // menu.setHasMenu(RightsHelper.testRights(roleRights,
	 * // menu.getMENU_ID())); // if (menu.isHasMenu()) { // List<Menu> subMenuList
	 * = menu.getSubMenu(); // for (Menu sub : subMenuList) { //
	 * sub.setHasMenu(RightsHelper.testRights( // roleRights, sub.getMENU_ID())); //
	 * if (sub.isHasMenu()) { // List<Menu> triMenuList = sub // .getSubMenu(); //
	 * for (Menu triMenu : triMenuList) { // triMenu.setHasMenu(RightsHelper //
	 * .testRights( // roleRights, // triMenu.getMENU_ID())); // } // } // } // } //
	 * } // } // session.setAttribute(Const.SESSION_allmenuList, allmenuList); // //
	 * 菜单权限放入session中 // } else { //// allmenuList = (List<Menu>) session ////
	 * .getAttribute(Const.SESSION_allmenuList); // allmenuList =
	 * menuService.listAllMenu(); // if (Tools.notEmpty(roleRights)) { // for (Menu
	 * menu : allmenuList) { // menu.setHasMenu(RightsHelper.testRights(roleRights,
	 * // menu.getMENU_ID())); // if (menu.isHasMenu()) { // List<Menu> subMenuList
	 * = menu.getSubMenu(); // for (Menu sub : subMenuList) { //
	 * sub.setHasMenu(RightsHelper.testRights( // roleRights, sub.getMENU_ID())); //
	 * if (sub.isHasMenu()) { // List<Menu> triMenuList = sub // .getSubMenu(); //
	 * for (Menu triMenu : triMenuList) { // triMenu.setHasMenu(RightsHelper //
	 * .testRights( // roleRights, // triMenu.getMENU_ID())); // } // } // } // } //
	 * } // } // session.setAttribute(Const.SESSION_allmenuList, allmenuList); // //
	 * 菜单权限放入session中 // } // // // 切换菜单===== // List<Menu> menuList = new
	 * ArrayList<Menu>(); // menuList = allmenuList; // // 切换菜单===== // // if (null
	 * == session.getAttribute(Const.SESSION_QX)) { //
	 * session.setAttribute(Const.SESSION_QX, this.getUQX(session)); // //
	 * 按钮权限放到session中 // } // // // FusionCharts 报表 // String strXML = "<graph
	 * caption='前12个月订单销量柱状图' xAxisName='月份' // yAxisName='值' " // +
	 * "decimalPrecision='0' formatNumberScale='0'><set // name='2013-05' value='4'
	 * " // + "color='AFD8F8'/><set name='2013-04' value='0' // color='AFD8F8'/><set
	 * name='2013-03' " // + "value='0' color='AFD8F8'/><set name='2013-02'
	 * value='0' // color='AFD8F8'/>" // + "<set name='2013-01' value='0'
	 * color='AFD8F8'/><set // name='2012-01' value='0' " // + "color='AFD8F8'/><set
	 * name='2012-11' value='0' // color='AFD8F8'/><set name='2012-10' " // +
	 * "value='0' color='AFD8F8'/><set name='2012-09' value='0' // color='AFD8F8'/>"
	 * // + "<set name='2012-08' value='0' color='AFD8F8'/><set // name='2012-07'
	 * value='0'" // + " color='AFD8F8'/><set name='2012-06' value='0' //
	 * color='AFD8F8'/></graph>"; // // mv.addObject("strXML", strXML); // //
	 * FusionCharts 报表
	 * 
	 * // mv.setViewName("system/admin/index"); mv.setViewName("system/admin/home");
	 * mv.addObject("user", user); IData param = IData.getInstance(request);
	 * param.put("user_id", user.getUSER_ID()); List<IData> menuIdList =
	 * userService.listMenuId(param); String menuList =
	 * JSONArray.fromObject(menuIdList).toString(); mv.addObject("menuIdList",
	 * menuList); } else { mv.setViewName("system/admin/login");// session失效后跳转登录页面
	 * }
	 * 
	 * } catch (Exception e) { mv.setViewName("system/admin/login");
	 * logger.error(e.getMessage(), e); } pd.put("SYSNAME",
	 * Tools.readTxtFile(Const.SYSNAME)); // 读取系统名称 mv.addObject("pd", pd); return
	 * mv; }
	 */

	/**
	 * 访问系统首页
	 */
	@RequestMapping(value = "/main/index")
	public ModelAndView main_index() {
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {

			// shiro管理的session
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			String token = pd.getString("token");
			Map<String, String> map = checkToken(token);

			User user = (User) session.getAttribute(Const.SESSION_USER);
			if (user != null) {

				User userr = (User) session.getAttribute(Const.SESSION_USERROL);
				if (null == userr) {
					user = userService.getUserAndRoleById(user.getUSER_ID());
					session.setAttribute(Const.SESSION_USERROL, user);
				} else {
					user = userr;
				}
				// 取得上下文中的role
				Role role = user.getRole();
				// 更新上下文种的role
				Role role1 = updateRoleRights(role);
				user.setRole(role1);
				String roleRights = role1 != null ? role1.getRIGHTS() : "";
				// 避免每次拦截用户操作时查询数据库，以下将用户所属角色权限、用户权限限都存入session
				session.setAttribute(Const.SESSION_ROLE_RIGHTS, roleRights); // 将角色权限存入session
				session.setAttribute(Const.SESSION_USERNAME, user.getUSERNAME()); // 放入用户名

				List<Menu> allmenuList = new ArrayList<Menu>();

				if (null == session.getAttribute(Const.SESSION_allmenuList)) {
					allmenuList = menuService.listAllMenu();
					if (Tools.notEmpty(roleRights)) {
						for (Menu menu : allmenuList) {
							menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMENU_ID()));
							if (menu.isHasMenu()) {
								List<Menu> subMenuList = menu.getSubMenu();
								for (Menu sub : subMenuList) {
									sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMENU_ID()));
									if (sub.isHasMenu()) {
										List<Menu> triMenuList = sub.getSubMenu();
										for (Menu triMenu : triMenuList) {
											triMenu.setHasMenu(
													RightsHelper.testRights(roleRights, triMenu.getMENU_ID()));
										}
									}
								}
							}
						}
					}
					session.setAttribute(Const.SESSION_allmenuList, allmenuList); // 菜单权限放入session中
				} else {
					// allmenuList = (List<Menu>) session
					// .getAttribute(Const.SESSION_allmenuList);
					allmenuList = menuService.listAllMenu();
					if (Tools.notEmpty(roleRights)) {
						for (Menu menu : allmenuList) {
							menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMENU_ID()));
							if (menu.isHasMenu()) {
								List<Menu> subMenuList = menu.getSubMenu();
								for (Menu sub : subMenuList) {
									sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMENU_ID()));
									if (sub.isHasMenu()) {
										List<Menu> triMenuList = sub.getSubMenu();
										for (Menu triMenu : triMenuList) {
											triMenu.setHasMenu(
													RightsHelper.testRights(roleRights, triMenu.getMENU_ID()));
										}
									}
								}
							}
						}
					}
					session.setAttribute(Const.SESSION_allmenuList, allmenuList); // 菜单权限放入session中
				}

				// 切换菜单=====
				List<Menu> menuList = new ArrayList<Menu>();
				menuList = allmenuList;
				// 切换菜单=====

				if (null == session.getAttribute(Const.SESSION_QX)) {
					session.setAttribute(Const.SESSION_QX, this.getUQX(session)); // 按钮权限放到session中
				}

				// FusionCharts 报表
				// String strXML = "<graph caption='前12个月订单销量柱状图' xAxisName='月份'
				// yAxisName='值' "
				// + "decimalPrecision='0' formatNumberScale='0'><set
				// name='2013-05' value='4' "
				// + "color='AFD8F8'/><set name='2013-04' value='0'
				// color='AFD8F8'/><set name='2013-03' "
				// + "value='0' color='AFD8F8'/><set name='2013-02' value='0'
				// color='AFD8F8'/>"
				// + "<set name='2013-01' value='0' color='AFD8F8'/><set
				// name='2012-01' value='0' "
				// + "color='AFD8F8'/><set name='2012-11' value='0'
				// color='AFD8F8'/><set name='2012-10' "
				// + "value='0' color='AFD8F8'/><set name='2012-09' value='0'
				// color='AFD8F8'/>"
				// + "<set name='2012-08' value='0' color='AFD8F8'/><set
				// name='2012-07' value='0'"
				// + " color='AFD8F8'/><set name='2012-06' value='0'
				// color='AFD8F8'/></graph>";
				// mv.addObject("strXML", strXML);
				// FusionCharts 报表

				mv.setViewName("system/admin/index");
				mv.addObject("user", user);
				mv.addObject("menuList", menuList);
			} else {
				mv.setViewName("system/admin/login");// session失效后跳转登录页面
				// mv.setViewName("redirect:"+Tools.readTxtFile(Const.SYSLOGIN));
			}

		} catch (Exception e) {
			mv.setViewName("system/admin/login");
			// mv.setViewName("redirect:"+Tools.readTxtFile(Const.SYSLOGIN));
			logger.error(e.getMessage(), e);
		}
		pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); // 读取系统名称
		mv.addObject("pd", pd);
		return mv;
	}

	/**
	 * 进入tab标签
	 * 
	 * @return
	 */
	@RequestMapping(value = "/tab")
	public String tab() {
		return "system/admin/tab";
	}

	/**
	 * 进入首页后的默认页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login_default")
	public String defaultPage() {
		return "system/admin/default";
	}

	/**
	 * 用户注销
	 * 
	 * @param session
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/logout")
	public ModelAndView logout(String token) throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();

		// shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		
		User user = (User) session.getAttribute(token);
		if(user != null && user.getUSER_ID() != null && user.getUSER_ID().length() > 0)
		{
			int res = userService.cleanUserToken(user);
		}
		session.removeAttribute(Const.SESSION_USER);
		session.removeAttribute(Const.SESSION_ROLE_RIGHTS);
		session.removeAttribute(Const.SESSION_allmenuList);
		session.removeAttribute(Const.SESSION_menuList);
		session.removeAttribute(Const.SESSION_QX);
		session.removeAttribute(Const.SESSION_userpds);
		session.removeAttribute(Const.SESSION_USERNAME);
		session.removeAttribute(Const.SESSION_USERROL);
		session.removeAttribute("changeMenu");

		pd = this.getPageData();
//        String params = pd.getString("params");
//		 //连接redis服务
//        jedisClient.del(params);

		// shiro销毁登录
		Subject subject = SecurityUtils.getSubject();
		subject.logout();

		pd = this.getPageData();
		String msg = pd.getString("msg");
		pd.put("msg", msg);

		pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); // 读取系统名称
		mv.setViewName("system/admin/login");
		mv.addObject("pd", pd);
		return mv;
	}

	/**
	 * 获取用户权限
	 */
	public Map<String, String> getUQX(Session session) {
		PageData pd = new PageData();
		Map<String, String> map = new HashMap<String, String>();
		try {
			String USERNAME = session.getAttribute(Const.SESSION_USERNAME).toString();
			pd.put(Const.SESSION_USERNAME, USERNAME);
			PageData role = userService.findByUId(pd);
			String ROLE_ID = null;
			if(role != null)
			{
				ROLE_ID = role.get("ROLE_ID").toString();
			}

			pd.put("ROLE_ID", ROLE_ID);

			PageData pd2 = new PageData();
			pd2.put(Const.SESSION_USERNAME, USERNAME);
			pd2.put("ROLE_ID", ROLE_ID);

			pd = roleService.findObjectById(pd);

			pd2 = roleService.findGLbyrid(pd2);
			if (null != pd2) {
				map.put("QX3", pd2.get("QX3").toString());
				map.put("QX4", pd2.get("QX4").toString());

				pd2.put("ROLE_ID", ROLE_ID);
				pd2 = roleService.findYHbyrid(pd2);
				map.put("C1", pd2.get("C1").toString());
				map.put("C2", pd2.get("C2").toString());
				map.put("C3", pd2.get("C3").toString());
				map.put("C4", pd2.get("C4").toString());
				map.put("Q1", pd2.get("Q1").toString());
				map.put("Q2", pd2.get("Q2").toString());
				map.put("Q3", pd2.get("Q3").toString());
				map.put("Q4", pd2.get("Q4").toString());
			}

			if(pd != null)
			{
				map.put("adds", pd.getString("ADD_QX"));
				map.put("dels", pd.getString("DEL_QX"));
				map.put("edits", pd.getString("EDIT_QX"));
				map.put("chas", pd.getString("CHA_QX"));
			}
			// System.out.println(map);

			this.getRemortIP(USERNAME);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return map;
	}

	private Role updateRoleRights(Role role) {
		Role role1 = new Role();
		try {
			role1 = roleService.getRoleById(role.getROLE_ID());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return role1;
	}

	/**
	 * 验证token
	 */
	public Map<String, String> checkToken(String token) {
		Map<String, String> map = new HashMap<String, String>();
		Claims claims = JwtTokenUtils.phaseToken(token);
		map.put("uid", claims.get("uid").toString());
		return map;
	}

	/**
	 * 修改平台密码
	 */
	@RequestMapping(value = "/user/updatePassword")
	@ResponseBody
	public Object updatePassword(@RequestParam("callback") String callback) {
		Gson gson = new Gson();
		Map<String, Object> result = new HashMap<>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String newPassword = pd.get("PASSWORD_NEW").toString();
		String oldPassword2 = pd.get("PASSWORD_OLD").toString();
		try {
			pd = userService.findByUiId(pd);
			// 根据ID读取
			String oldpwd1 = pd.getString("PASSWORD");
			SimpleHash oldpwd = new SimpleHash("SHA-1", pd.getString("USERNAME"), oldPassword2);
			if (oldpwd.toString().equals(oldpwd1.toString())) {
				pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), newPassword).toString());
				userService.editPwd(pd);
				result.put("msg", "成功");
				result.put("code", "200");
			} else {
				result.put("msg", "旧密码错误，请重新输入!");
				result.put("code", "201");
			}
		} catch (Exception e) {
			result.put("msg", "系统异常，稍后再试！");
			result.put("code", "202");
		} 
		return callback + "(" + gson.toJson(result) + ")";
	}
	
}
